package com.itheima.service;

import com.itheima.mapper.BrowseGoodsRecordMapper;
import com.itheima.mapper.ItemMapper;
import com.itheima.pojo.BrowseGoodsRecord;
import com.itheima.pojo.Item;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrowseGoodsRecordService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    public void add(BrowseGoodsRecord browseGoodsRecord) {
        //调用BrowseGoodsRecordMapper.add()

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrowseGoodsRecordMapper
        BrowseGoodsRecordMapper mapper = sqlSession.getMapper(BrowseGoodsRecordMapper.class);

        //4. 调用方法
        mapper.add(browseGoodsRecord);

        // 提交事务
        sqlSession.commit();
        // 释放资源
        sqlSession.close();
    }

    public List<BrowseGoodsRecord> selectByUserId(Integer userId) {
        //调用BrowseGoodsRecordMapper.selectByUserId()

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrowseGoodsRecordMapper
        BrowseGoodsRecordMapper mapper = sqlSession.getMapper(BrowseGoodsRecordMapper.class);

        //4. 调用方法
        List<BrowseGoodsRecord> browseGoodsRecord = mapper.selectByUserId(userId);

        // 释放资源
        sqlSession.close();

        return browseGoodsRecord;
    }

    public Integer selectByItemName(String itemName) {
        //调用BrowseGoodsRecordMapper.selectByItemName()

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrowseGoodsRecordMapper
        BrowseGoodsRecordMapper mapper = sqlSession.getMapper(BrowseGoodsRecordMapper.class);

        //4. 调用方法
        Integer totalQuantity = mapper.selectByItemName(itemName);

        // 释放资源
        sqlSession.close();

        return totalQuantity;
    }
}
